package com.wh.wisdomsite.xbox.server.controller.al;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.al.entity.AlarmSign;
import com.wh.wisdomsite.xbox.al.service.IAlarmSignService;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.al.AlarmSignIn;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 警报预警controller
 *
 * @author 杨世强
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.al
 * @date 2018年08月08日 17:39
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/alarmSign")
public class AlarmSignController {
    private static final Log logger = LogFactory.getLog(AlarmSignController.class);

    @Autowired
    private IAlarmSignService iAlarmSignService;


    /**
     * 跳转到警报预警页面
     *
     * @return
     */
    @RequiresPermissions("rules:al_alarmSignDust_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index(@RequestParam(value = "alarmStatus", required = false) String alarmStatus,String alarmCategory, HttpServletRequest request) {
        request.setAttribute("alarmStatus", alarmStatus);
        request.setAttribute("alarmCategory", alarmCategory);
        return "al/alarmSign/alarmSignList";
    }

    /**
     * 跳转到警报处理
     *
     * @return
     */
    @RequestMapping(value = "/resolve.do", method = RequestMethod.GET)
    public String resolve(String alId, HttpServletRequest request) {
        logger.info("警报处理跳转-->>开始");
        if (StringUtils.isNotEmpty(alId)) {
            Map<String, Object> alarmSign = iAlarmSignService.getMapById(alId);
            AlarmSign tempAlarmSign = new AlarmSign();
            tempAlarmSign.setAlarmSubdivided(alarmSign.get("alarmSubdivided").toString());
            alarmSign.put("measureUnit", tempAlarmSign.getMeasureUnit());
            request.setAttribute("alarmSign", alarmSign);
        }
        logger.info("警报处理跳转-->>结束");
        return "al/alarmSign/alarmResolve";
    }

    /**
     * 保存处理结果
     *
     * @param alarmSign
     * @param response
     */
    @RequiresPermissions("rules:al_alarmSign_resolve")
    @RequestMapping(value = "/saveResolve.do", method = RequestMethod.POST)
    public void saveResolve(AlarmSign alarmSign, HttpServletResponse response) {
        try {
            logger.info("保存处理结果-->>开始");
            AlarmSign tempAlarmSign = iAlarmSignService.selectById(alarmSign.getAlId());
            tempAlarmSign.setAlarmStatus("2");
            tempAlarmSign.setResolveUser(alarmSign.getResolveUser());
            tempAlarmSign.setResolveTime(alarmSign.getResolveTime());
            tempAlarmSign.setResolveContent(alarmSign.getResolveContent());
            iAlarmSignService.updateById(tempAlarmSign);
            logger.info("保存处理结果-->>结束");
            response.getWriter().write(JsonUtil_Org.returnTrue("保存处理成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("保存处理结果-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取警示集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:al_alarmSign_find")
    @RequestMapping(value = "/getAlarmList.do")
    public void getAlarmList(HttpServletResponse response, AlarmSignIn in) {
        try {
            logger.info("加载警报预警列表-->>开始");
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<AlarmSign> page = new Page<AlarmSign>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<AlarmSign> ewAlarmSign = new EntityWrapper<AlarmSign>();
            ewAlarmSign.setEntity(new AlarmSign());
            if (StringUtils.isNotEmpty(in.getPrId())) {
                ewAlarmSign.eq("a.prId", in.getPrId());
            }
            if (StringUtils.isNotEmpty(in.getAlarmType())) {
                ewAlarmSign.eq("a.alarmType", in.getAlarmType());
            }
            if (StringUtils.isNotEmpty(in.getAlarmStatus())) {
                ewAlarmSign.eq("a.alarmStatus", in.getAlarmStatus());
            }
            if (StringUtils.isNotEmpty(in.getAlarmCategory())) {
                ewAlarmSign.eq("a.alarmCategory", in.getAlarmCategory());
            }
            if (StringUtils.isNotEmpty(in.getStartDate()) && StringUtils.isNotEmpty(in.getEndDate())) {
                ewAlarmSign.between("a.alarmTime", in.getStartDate(), in.getEndDate());
            }
            //若不是超级管理员则根据用户权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewAlarmSign = UserUtils.setEntityWrapper(ewAlarmSign, "co", "off", "pr");
            }
            ewAlarmSign.orderBy("a.createDate", false);
            Page<Map<String, Object>> alarmSignPage = iAlarmSignService.getMapsPage(page, ewAlarmSign);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (alarmSignPage.getRecords().size() > 0) {
                for (Map<String, Object> alarmSign : alarmSignPage.getRecords()) {
                    JSONObject object = new JSONObject(alarmSign);
                    object.put("alarmTime", DateTool.getFormatDateByMs(alarmSign.get("alarmTime")));
                    if (alarmSign.get("project") != null) {
                        object.put("project", new JSONObject(alarmSign.get("project")));
                    }
                    if (alarmSign.get("unitOperator") != null) {
                        object.put("unitOperator", new JSONObject(alarmSign.get("unitOperator")));
                    }
                    array.put(object);
                }
            }
            json.put("total", alarmSignPage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载警报预警列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 警报预警列表数据详情
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("alarmSignDesc.do")
    public String alarmSignDesc(String id, HttpServletRequest request) {
        try {
            logger.info("警报预警列表详情-->>开始");
            Map<String, Object> alarmSign = iAlarmSignService.getMapById(id);
            AlarmSign tempAlarmSign = new AlarmSign();
            tempAlarmSign.setAlarmSubdivided(alarmSign.get("alarmSubdivided").toString());
            alarmSign.put("measureUnit", tempAlarmSign.getMeasureUnit());
            request.setAttribute("alarmSign", alarmSign);
            logger.info("警报预警列表详情-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "al/alarmSign/alarmSignDesc";
    }

    /**
     * 获取未处理警报数据
     *
     * @param response
     */
    @RequestMapping("/getUnresolveAlarm.do")
    public void getUnresolveAlarm(HttpServletResponse response) {
        try {
            logger.info("获取未处理警报-->>开始");
            Page<AlarmSign> page = new Page<AlarmSign>();
            page.setCurrent(1);
            page.setSize(Integer.MAX_VALUE);
            //设置条件
            EntityWrapper<AlarmSign> ewAlarmSign = new EntityWrapper<AlarmSign>();
            ewAlarmSign.setEntity(new AlarmSign());
            ewAlarmSign.eq("a.alarmStatus", "1");
            //若不是超级管理员则根据用户权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewAlarmSign = UserUtils.setEntityWrapper(ewAlarmSign, "co", "off", "pr");
            }
            ewAlarmSign.orderBy("a.createDate", false);
            Page<Map<String, Object>> alarmSignPage = iAlarmSignService.getMapsPage(page, ewAlarmSign);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (alarmSignPage.getRecords().size() > 0) {
                for (Map<String, Object> alarmSign : alarmSignPage.getRecords()) {
                    JSONObject object = new JSONObject(alarmSign);
                    array.put(object);
                }
            }
            json.put("total", alarmSignPage.getRecords().size());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("获取未处理警报-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取警报总条数、未处理条数、已处理条数
     * @param response
     * @return
     */
    @RequestMapping("/getAlarmData.do")
    public void getAlarmData(HttpServletResponse response,String alarmCategory) {
        try {
            logger.info("首页获取警报数据-->>开始");
            EntityWrapper<AlarmSign> ewAlarmSign = new EntityWrapper<AlarmSign>();
            ewAlarmSign.setEntity(new AlarmSign());
            //若不是超级管理员则根据用户权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewAlarmSign = UserUtils.setEntityWrapper(ewAlarmSign, "co", "off", "pr");
            }
            if(StringUtils.isNotEmpty(alarmCategory)){
                ewAlarmSign.eq("a.alarmCategory", alarmCategory);
            }
            Map<String , Object> alarmSign = iAlarmSignService.getAlarmNumber(ewAlarmSign,"1");
            JSONObject json = new JSONObject();
            //总条数
            Integer totalNum = 0;
            //未处理条数
            Integer untreatedNum = 0;
            //已处理条数
            Integer handleNum = 0;
            if(null != alarmSign.get("totalNum")){
                totalNum = Integer.parseInt(alarmSign.get("totalNum").toString());
            }
            if(null != alarmSign.get("untreatedNum")){
                untreatedNum = Integer.parseInt(alarmSign.get("untreatedNum").toString());
            }
            handleNum = totalNum - untreatedNum;
            json.put("totalNum",totalNum);
            json.put("handleNum",handleNum);
            json.put("untreatedNum",untreatedNum);
            ResManager.getJsonOut(response).print(json);
            logger.info("首页获取警报数据-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("首页获取警报数据-->>Exception" + e.getMessage());
        }
    }

}
